import { BASE_URL } from '../const.js'

function toLogin() {
	uni.redirectTo({
		url: '/pages/login/login.vue'
	})
}
// 请求封装
const api = {
	requset(url = '', data = {}, method = 'GET', header = {}) {
		console.log('appppppppp', url)
		// let token = uni.getStorageSync('login_token')
		// if (!token) {
		// 	toLogin()
		// 	return false
		// }
		console.log('22222')
		return new Promise((resolve, reject) => {
			uni.showLoading()
			console.log('sssdsd')
			uni.request({
				url: BASE_URL + url,
				data,
				header: {
					'content-type': 'application/json',
					...header
				},
				method,
				timeout: 100000,
				dataType: 'json',
				responseType: 'text',
				success: (res) => {
					console.log('api.....', res)
					if (res.errMsg == 'request:ok') {
						// 未登录
						if (res.status === '401') {
							toLogin()
							return false
						}
						resolve(res.data)
					} else {
						reject(res.data.message)
					}
				},
				fail: (err) => {
					console.warn(`request fail, ${err}`)
					reject(err)
				},
				complete: (c) => {
					console.log('ccdsss', c)
					uni.hideLoading()
				}
			})
		})
	},
	
	post(url = '', data = {}, header = {}) {
		return api.requset(url, data, 'POST', header)
	},
	
	get(url = '', data = {}, header = {}) {
		return api.requset(url, data, 'GET', header)
	}
}

export default api
